package net.jcip.chapter3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * ConnectionDispenser
 * <p/>
 * Using ThreadLocal to ensure thread confinement   使用  threadLocal 来保证线程封闭性
 * <p>
 * confinement:
 * 监禁
 * 英式:[kənˈfaɪnmənt];美式:[kənˈfaɪnmənt]
 * 本地释义: n. 监禁，关押；分娩，生产
 *
 * @author Brian Goetz and Tim Peierls
 */
public class ConnectionDispenser {
    static String DB_URL = "jdbc:mysql://localhost/mydatabase";

    private static  ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() {
        public Connection initialValue() {
            try {
                return DriverManager.getConnection(DB_URL);
            } catch (SQLException e) {
                throw new RuntimeException("Unable to acquire Connection, e");
            }
        }
    };

    public static  Connection getConnection() {
        return connectionHolder.get();
    }
}
